/*    

    bobbietalk - a visual programming environment for toy robotics

    Copyright (C) 2013  Roberto Tiella

    This program is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program.  If not, see <http://www.gnu.org/licenses/>.

*/
package bobbietalk.semantics.interpreter.robots.remote;

import bobbietalk.Utilities;
import bobbietalk.gui.ProgrammingBlock;
import bobbietalk.semantics.compiler.BlockGraph;
import java.io.IOException;
import java.net.Socket;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 * @author roberto
 */
public class InterpreterController {

    private Socket socket;
    private Interpreter interpr;
    private Thread interprThread;
    private List<String> messages = new ArrayList<>();

    public boolean init(List<ProgrammingBlock> blocks, List<String> messages) {

        BlockGraph g = BlockGraph.fromBlocks(blocks);


        if (!g.checkSemantics(messages)) {

            closeSocket();
            return false;
        }



        try {
            socket = new Socket("localhost", 7000);
            interpr = new Interpreter(socket, g);
            interprThread = new Thread(interpr);


        } catch (Exception ex) {

            messages.add("can't contact simulator:" + ex);
            closeSocket();
            return false;

        }

        return true;

    }

    public void startProgram() {

        interprThread.start();


    }

    public void stopProgram() {
        try {

            interpr.terminate();

            interprThread.join();

            if (interpr.getStatus() == Interpreter.Status.ERROR) {

                messages.addAll(interpr.getMessages());
                closeSocket();


            }

        } catch (InterruptedException ex) {
            Utilities.getLogger().log(Level.SEVERE, null, ex);
            closeSocket();

        }

    }

    private void closeSocket() {

        if (socket != null) {

            try {

                socket.close();
            } catch (IOException ex) {
                Utilities.getLogger().log(Level.SEVERE, null, ex);
            }

        }
    }
}
